from django.shortcuts import render, HttpResponse, redirect
from app01 import models
# Create your views here.


# def index(request):
#     # 正向操作
#     # v = models.User.objects.all()
#     # for i in v:
#     #     print(i.user, i.pwd, i.ut.name)
#     # models.User.objects.all().values('user', 'ut__name')
#
#     # c = models.UserType.objects.all()
#     # for itme in c:
#     #     itme.name,
#     #     itme.id,
#     #     itme.user_set.all()
#     # models.UserType.objects.all().values('name', 'user__pwd', 'user__user')
#     return render(request, 'index.html')


def ajax(request):
    return render(request, 'ajax.html')


def ajax_json(request):
    print(request.POST)
    ret = {'code': True, 'data': request.POST.get('username')}
    import json
    return HttpResponse(json.dumps(ret))


def upload(request):
    return render(request, 'upload.html')


def upload_file(request):
    username = request.POST.get('username')
    fafafa = request.FILES.get('fafafa')
    import os
    img_path = os.path.join('static/image/', fafafa.name)
    with open(img_path, 'wb') as f:
        for item in fafafa.chunks():
            f.write(item)

    ret = {'code': True, 'data': img_path}
    import json
    return HttpResponse(json.dumps(ret))

from .check_code import create_validate_code
from io import BytesIO


def check_code(request):
    """
    验证码
    :param request:
    :return:
    """
    stream = BytesIO()
    img, code = create_validate_code()
    img.save(stream, 'PNG')
    request.session['CheckCode'] = code
    return HttpResponse(stream.getvalue())


def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    if request.method == "POST":
        if request.session['CheckCode'].upper() == request.POST.get('check_code').upper():
            user = request.POST.get('user')
            pwd = request.POST.get('pwd')
            print(user, pwd)
            c_user = models.User.objects.filter(user=user).count()
            if c_user:
                user_info = models.User.objects.filter(user=user)
                for i in user_info:
                    if i.pwd == pwd and i.user == user:
                        print('OK')
                        request.session['user'] = user
                        request.session['is_login'] = True
                        return redirect('/index/')
                    else:
                        return render(request, 'login.html')
            else:
                return render(request, 'login.html')
        else:
            return render(request, 'login.html')


def auth(func):
    def wrap(request, *args, **kwargs):
        if request.session.get('is_login', False) is not True:
            return redirect('/login/')
        return func(request, *args, **kwargs)
    return wrap


@auth
def index(request):
    user = request.session['user']
    print(1111)
    return render(request, 'index.html', {'user': user})


